<?php

/**
 * 后台Action
 */
// 定义是后台
namespace Common\Controller;

use Common\Controller\AppframeController;
use Com\WechatAuth;

define ( 'IN_ADMIN', true );
class AdminbaseController extends AppframeController {


	public $wk;
	public $wxconfig;


	function _initialize() {
		parent::_initialize ();
	
		define ( 'UID', session("ADMIN_ID") );
		if (! UID) { // 还没登录 跳转到登录页面
		            
			// $this->error("您还没有登录！",U("admin/public/login"));
			if (IS_AJAX) {
				$this->error ( "您还没有登录！", U ( "Public/login" ) );
			} else {
				header ( "Location:" . U ( "Public/login" ) );
				exit ();
			}
		}
		
		$users_obj = D ( "Admin" );
	
		$this->user = $users_obj->where ( array("uid"=>UID) )->find ();


		
		$rule = strtolower ( MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME );


		if(!check_url($rule,UID)){
			
			$this->error ( "禁止访问！" );
			
		}
		$this->wxconfig=F("Config_weixin");



		$this->get_c_auth();
		
		$this->assign ( "admin", $this->user );
		
		$this->initMenu ();
	}

	public function  get_c_auth(){


		$s=M("WxToken")->order("id desc")->find();




		$this->wk = new WechatAuth($this->wxconfig["WX_APPID"], $this->wxconfig["WX_APPSECRET"], $s["token"]);




		$this->wk->setJsApiTicket($s["ticket"]);

		$jssign=$this->wk->getSignPackage();

		$this->assign("jssign",$jssign);













	}
	/**
	 * 初始化后台菜单
	 */
	public function initMenu() {



		
			$submenus=D("AuthRule")->s(MODULE_NAME);


	
		$this->assign("submenus",$submenus);

		
		$now_menu = D ( "AuthRule" )->where ( array (
				"name" => MODULE_NAME . "/" . CONTROLLER_NAME . "/" . ACTION_NAME
		) )->cache(true)->find ();
		
		//print_r($now_menu);
		
		$this->assign ( 'menuid', $now_menu ['id'] );
		$this->assign ( 'menu_title', $now_menu [title] );
		if ($now_menu ['right']) {
			$p_menu = D ( "AuthRule" )->where ( array (
					"id" => $now_menu ['parentid']
			) )->cache(true)->select ();
			$t_menu = D ( "AuthRule" )->where ( array (
					"parentid" => $now_menu ['parentid'],
					"right" => 1 ,
					"status" => 1 ,
					"display" => 1 ,
			) )->cache(true)->order("listorder DESC")->select ();
				
			$right_menu = array_merge ( $p_menu, $t_menu );
		} else {
			$p_menu = D ( "AuthRule" )->where ( array (
					"id" => $now_menu ['id']
			) )->cache(true)->select ();
			$t_menu = D ( "AuthRule" )->where ( array (
					"parentid" => $now_menu ['id'],
					"right" => 1 ,
					"status" => 1 ,
					"display" => 1 ,
			) )->cache(true)->order("listorder DESC")->select ();
				
			$right_menu = array_merge ( $p_menu, $t_menu );
		}
		
		
		
		//	echo $f_lanmu;
		if ($right_menu) {
				
			$this->assign ( 'right_menu', $right_menu );
		}
		
		$p1 = M ( "AuthRule" )->where ( array (	"id" => $now_menu ['id']	) )->cache(true)->getField ("parentid");
		if($p1) $f_lanmu=$p1.",".$now_menu ['id'];
		
		$p2 = M ( "AuthRule" )->where ( array (	"id" => $p1	) )->cache(true)->getField ("parentid");
		if($p2) $f_lanmu=$p2.",".$f_lanmu;
		
		$p3 = M ( "AuthRule" )->where ( array (	"id" => $p2	) )->cache(true)->getField ("parentid");
		if($p3) $f_lanmu=$p3.",".$f_lanmu;
		
		$p4 = M( "AuthRule" )->where ( array ("id" => $p3) )->cache(true)->getField ("parentid");
		if($p4) $f_lanmu=$p4.",".$f_lanmu;
		
		$this->assign ( 'f_lanmu', $f_lanmu );
		
		$ss=explode(",",$f_lanmu);
		
		foreach ($ss as $key=>$v){
		
			$brand[]= M( "AuthRule" )->where ( array ("id" => $v) )->cache(true)->find ();
		
		}

		$this->assign ( 'brand', $brand );
		
	}

	
	
	/**
	 * 权限检测
	 * 
	 * @param string $rule
	 *        	检测的规则
	 * @param string $mode
	 *        	check模式
	 * @return boolean
	 * @author 朱亚杰 <xcoolcc@gmail.com>
	 */
	final protected function checkRule($rule, $type = AuthRuleModel::RULE_URL, $mode = 'url') {
		if (IS_ROOT) {
			return true; // 管理员允许访问任何页面
		}
		static $Auth = null;
		if (! $Auth) {
			$Auth = new \Think\Auth ();
		}
		if (! $Auth->check ( $rule, UID, $type, $mode )) {
			return false;
		}
		return true;
	}
	
	/**
	 * 检测是否是需要动态判断的权限
	 * 
	 * @return boolean null 返回false则表示当前访问无权限
	 *         返回null，则会进入checkRule根据节点授权判断权限
	 *        
	 * @author 朱亚杰 <xcoolcc@gmail.com>
	 */
	protected function checkDynamic() {
		if (IS_ROOT) {
			return true; // 管理员允许访问任何页面
		}
		return null; // 不明,需checkRule
	}
	

	
	/**
	 * 排序 排序字段为listorders数组 POST 排序字段为：listorder
	 */
	protected function _listorders($model) {
		if (! is_object ( $model )) {
			return false;
		}
		$pk = $model->getPk (); // 获取主键名称
		$ids = $_POST ['listorders'];
		
		//print_r($ids);
		foreach ( $ids as $key => $r ) {
			$data ['listorder'] = $r;
			$data [$pk]= $key ;
			
			$model->save ( $data );
		}
		return true;
	}
	

 function check_access($roleid) {
		
		// 如果用户角色是1，则无需判断
		if ($roleid == 1) {
			return true;
		}
		$role_obj = D ( "Role" );
		$role = $role_obj->field ( "status" )->where ( "id=$roleid" )->find ();
		if (! empty ( $role ) && $role ['status'] == 1) {
			$group = MODULE_NAME;
			$model = CONTROLLER_NAME;
			$action = ACTION_NAME;
			if (MODULE_NAME . CONTROLLER_NAME . ACTION_NAME != "AdminIndexindex") {
				$access_obj = M ( "Access" );
				$count = $access_obj->where ( "role_id=$roleid and g='$group' and m='$model' and a='$action'" )->count ();
				return $count;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * action访问控制,在 **登陆成功** 后执行的第一项权限检测任务
	 *
	 * @return boolean null `===` 进行判断
	 *        
	 *         返回 **false**, 不允许任何人访问(超管除外)
	 *         返回 **true**, 允许任何管理员访问,无需执行节点权限检测
	 *         返回 **null**, 需要继续执行节点权限检测决定是否允许访问
	 */
	final protected function accessControl() {
		if (IS_ROOT) {
			return true; // 管理员允许访问任何页面
		}
		$allow = C ( 'ALLOW_VISIT' );
		$deny = C ( 'DENY_VISIT' );
		$check = strtolower ( CONTROLLER_NAME . '/' . ACTION_NAME );
		if (! empty ( $deny ) && in_array_case ( $check, $deny )) {
			return false; // 非超管禁止访问deny中的方法
		}
		if (! empty ( $allow ) && in_array_case ( $check, $allow )) {
			return true;
		}
		return null; // 需要检测节点权限
	}
	
	/**
	 * 状态转换
	 */
	public function changestatus() {
		$id = $_REQUEST[id];
		$r = $this->db->where(array("id" => $id))->find();
	
		if ($r) {
			$data[status] = $r['status'] ? 0 : 1;
			$data[id]=$id;
			$result=  $this->db->save($data);
			if ($result !== false) {
	
				$this->success("转换成功！");
	
			} else {
				$this->error("转换失败！");
			}
		} else {
			$this->error("不存在！");
		}
	}
	
	
	public function change(){
		 
		$c=array("status","tui","top","display","ismenu","right","shenhe","new");
		
		$field =I("get.field");
		
	
		$value=I("get.value")?I("get.value"):"";
		$id=I("get.id");
		if(!$field||!$id||!in_array($field,$c)){
	
			$this->error("缺少参数！");
		}
		 
		$data[$field]=$value;
		$data[id]=$id;
		 
		if ($this->db->save($data) !== false) {
			$this->success("更新成功！");
		} else {
			$this->error("更新失败！");
		}
		 
		 
	}
	
	
	function delete(){
		if(isset($_GET['id'])){
			$id = intval(I("get.id"));
				
			if ($this->db->delete($id)) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
		if(isset($_POST['ids'])){
			$ids=I("param.ids");
		
			$map[id]=array("in",$ids);
	
			if ($this->db->where($map)->delete()) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}


	function add_log($content,$modal_id){

		$log=array(
			"content"=>$content,
			"modal_id"=>$modal_id,
			"uid"=>UID,
			"controller"=>CONTROLLER_NAME,
			"action"=>ACTION_NAME,
			"inputtime"=>time()
		);


		M("Log")->add($log);




	}
	
	
	function getExcel($tmp,$titles,$data,$header,$fileName){
	
	
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Reader.Excel5");
		import("Org.Util.PHPExcel.Writer.Excel5");
		import("Org.Util.PHPExcel.IOFactory.php");
	
	
	
	
	
		$objPHPExcel=new \PHPExcel();
		
		if($tmp){
		$objPHPExcel=new \PHPExcel_Reader_Excel5();
		//载入文件
		
		
		$tmp=EXCELS."/".$tmp.".xls";
		$objPHPExcel=$objPHPExcel->load($tmp);
		}
		$objActSheet = $objPHPExcel->getActiveSheet();
	
	
	
	
	
	
		$column = 1;
	
	
	
		foreach($titles as $v){
	
	
			$objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A'.$column, $v);
			$column++;
		}
	
		//判断是否有列标题  写入
		if($header){
			$span = 0;
			foreach($header as $v){
				$j = $this->stringFromColumnIndex($span);
				$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($j.$column, $v);
	
				if(!$tmp){
				$objPHPExcel->getActiveSheet()->getColumnDimension($j)->setAutoSize(true);
				}
				$span ++;
			}
			$column++;
		}
	
	
	
		foreach($data as $key => $rows){ //行写入
			$span = 0;
			foreach($rows as $keyName=>$value){// 列写入
				$j = $this->stringFromColumnIndex($span);
				$objActSheet->setCellValue($j.$column, $value,\PHPExcel_Cell_DataType::TYPE_STRING);
				$span++;
			}
			 
			//$objActSheet->getColumnDimension($j)->setAutoSize(true);
			$column++;
		}
	
	
	
	
		//设置样式
		$s1='A';
		$s2=$titles?count($titles)+1:1;
		$e1=$this->stringFromColumnIndex(count($header)-1);
		$e2=$titles?count($data)+count($titles)+1:count($data)+1;
	
		$styleArray = array(
				'borders' => array(
						'allborders' => array(
	
								'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
	
						),
				),
				'alignment' => array(
	
						'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
	
				)
	
		);
	
	
	
		$objActSheet->getStyle($s1.$s2.":".$e1.$e2)->applyFromArray($styleArray);
	
	
	
		$fileName = iconv("utf-8", "gb2312", $fileName.".xls");
	
		//重命名表
		// $objPHPExcel->getActiveSheet()->setTitle('test');
		//设置活动单指数到第一个表,所以Excel打开这是第一个表
		$objPHPExcel->setActiveSheetIndex(0);
	
	
		$filename=iconv('utf-8', 'gb2312', $fileName);
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=\"$fileName\"");
		header('Cache-Control: max-age=0');
	
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output'); //文件通过浏览器下载
		exit;
	}
	
	function stringFromColumnIndex($pColumnIndex = 0)
	{
		//  Using a lookup cache adds a slight memory overhead, but boosts speed
		//  caching using a static within the method is faster than a class static,
		//      though it's additional memory overhead
		static $_indexCache = array();
	
		if (!isset($_indexCache[$pColumnIndex])) {
			// Determine column string
			if ($pColumnIndex < 26) {
				$_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
			} elseif ($pColumnIndex < 702) {
				$_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . chr(65 + $pColumnIndex % 26);
			} else {
				$_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . chr(65 + $pColumnIndex % 26);
			}
		}
		return $_indexCache[$pColumnIndex];
	}
	
}

?>
